package util;

import io.jsonwebtoken.*;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;


public class JwtUtil {
    private String key;
    private long ttl;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成JWT
     * @param id
     * @param subject
     * @param roles
     * @return
     */
    public String createJWT(String id,String subject ,String roles){
        long nowMillis=System.currentTimeMillis();
        Date now=new Date(nowMillis);
        JwtBuilder jwtBuilder= Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256,"itcast").claim("roles",roles);
        ttl=3600000;
        if(ttl>0){
            jwtBuilder.setExpiration(new Date(nowMillis+ttl));
        }
        return jwtBuilder.compact();
    }




    /**
     * 解析jwt
     * @param jwt
     * @return
     */
    public  Claims parseJWT(String jwt){
        return Jwts.parser()
                .setSigningKey("itcast")
                .parseClaimsJws(jwt)
                .getBody();
    }



}
